package guanli;

import until.DBUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class SendExpressManagePanel extends JPanel {
    private JTable table;
    private DefaultTableModel model;
    // 与表结构一致的状态枚举
    private final String[] STATUS_OPTIONS = {"待寄出", "已寄出"};

    public SendExpressManagePanel() {
        setLayout(new BorderLayout());

        JLabel title = new JLabel("寄快递记录管理", SwingConstants.CENTER);
        title.setFont(new Font("微软雅黑", Font.BOLD, 22));
        add(title, BorderLayout.NORTH);

        // 表格模型 - 调整列名与表结构匹配
        model = new DefaultTableModel(new String[]{
                "ID", "寄件人姓名", "寄件人电话", "收件人姓名", "收件人电话", "收件地址",
                "柜子ID", "柜子尺寸", "取件码", "状态", "创建时间", "付款方式"
        }, 0);
        table = new JTable(model);
        loadData();

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);

        // 操作按钮
        JPanel btnPanel = new JPanel();

        JButton btnAdd = new JButton("添加记录");
        JButton btnDelete = new JButton("删除选中");
        JButton btnRefresh = new JButton("刷新");

        btnAdd.addActionListener(e -> addRecord());
        btnDelete.addActionListener(e -> deleteSelected());
        btnRefresh.addActionListener(e -> loadData());

        btnPanel.add(btnAdd);
        btnPanel.add(btnDelete);
        btnPanel.add(btnRefresh);
        add(btnPanel, BorderLayout.SOUTH);
    }

    private void loadData() {
        model.setRowCount(0);
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             // 显式指定所有字段，确保与表结构一致
             ResultSet rs = stmt.executeQuery(
                     "SELECT id, sender_name, sender_phone, recipient_name, recipient_phone, " +
                             "recipient_address, locker_id, size, code, status, create_time, payment_method " +
                             "FROM send_express")) {

            while (rs.next()) {
                model.addRow(new Object[]{
                        rs.getInt("id"),
                        rs.getString("sender_name"),
                        rs.getString("sender_phone"),
                        rs.getString("recipient_name"),
                        rs.getString("recipient_phone"),
                        rs.getString("recipient_address"),
                        rs.getInt("locker_id"),
                        rs.getString("size"),
                        rs.getString("code"),
                        rs.getString("status"),
                        rs.getTimestamp("create_time"),
                        rs.getString("payment_method")
                });
            }
        } catch (SQLException e) {
            e.printStackTrace(); // 打印完整堆栈信息
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage());
        }
    }

    private void addRecord() {
        // 添加所有必要字段的输入框
        JTextField senderNameField = new JTextField();
        JTextField senderPhoneField = new JTextField();
        JTextField recipientNameField = new JTextField();
        JTextField recipientPhoneField = new JTextField();
        JTextField addressField = new JTextField();
        JTextField codeField = new JTextField();
        JTextField lockerField = new JTextField();
        JComboBox<String> statusBox = new JComboBox<>(STATUS_OPTIONS);
        JComboBox<String> paymentBox = new JComboBox<>(new String[]{"到付", "已支付"});
        JComboBox<String> sizeBox = new JComboBox<>(new String[]{"小柜", "中柜", "大柜"});

        // 构建输入面板
        JPanel panel = new JPanel(new GridLayout(0, 2));
        panel.add(new JLabel("寄件人姓名:"));
        panel.add(senderNameField);
        panel.add(new JLabel("寄件人电话:"));
        panel.add(senderPhoneField);
        panel.add(new JLabel("收件人姓名:"));
        panel.add(recipientNameField);
        panel.add(new JLabel("收件人电话:"));
        panel.add(recipientPhoneField);
        panel.add(new JLabel("收件地址:"));
        panel.add(addressField);
        panel.add(new JLabel("柜子尺寸:"));
        panel.add(sizeBox);
        panel.add(new JLabel("取件码:"));
        panel.add(codeField);
        panel.add(new JLabel("柜子ID:"));
        panel.add(lockerField);
        panel.add(new JLabel("状态:"));
        panel.add(statusBox);
        panel.add(new JLabel("付款方式:"));
        panel.add(paymentBox);

        int result = JOptionPane.showConfirmDialog(this, panel, "添加寄件记录", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            try {
                // 获取并验证输入
                String senderName = senderNameField.getText().trim();
                String senderPhone = senderPhoneField.getText().trim();
                String recipientName = recipientNameField.getText().trim();
                String recipientPhone = recipientPhoneField.getText().trim();
                String address = addressField.getText().trim();
                String size = (String) sizeBox.getSelectedItem();
                String code = codeField.getText().trim();
                String lockerIdStr = lockerField.getText().trim();
                String status = (String) statusBox.getSelectedItem();
                String payment = (String) paymentBox.getSelectedItem();

                // 输入验证
                if (senderName.isEmpty() || senderPhone.isEmpty() || recipientName.isEmpty() ||
                        recipientPhone.isEmpty() || address.isEmpty() || code.isEmpty() || lockerIdStr.isEmpty()) {
                    JOptionPane.showMessageDialog(this, "请填写所有必填字段", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                int lockerId = Integer.parseInt(lockerIdStr);

                // 验证柜子ID是否存在
                if (!validateLockerExists(lockerId)) {
                    return;
                }

                try (Connection conn = DBUtil.getConnection();
                     PreparedStatement ps = conn.prepareStatement(
                             "INSERT INTO send_express (sender_name, sender_phone, recipient_name, " +
                                     "recipient_phone, recipient_address, size, code, locker_id, status, payment_method) " +
                                     "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) {

                    ps.setString(1, senderName);
                    ps.setString(2, senderPhone);
                    ps.setString(3, recipientName);
                    ps.setString(4, recipientPhone);
                    ps.setString(5, address);
                    ps.setString(6, size);
                    ps.setString(7, code);
                    ps.setInt(8, lockerId);
                    ps.setString(9, status);
                    ps.setString(10, payment);

                    ps.executeUpdate();
                    JOptionPane.showMessageDialog(this, "记录添加成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                    loadData();
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(this, "柜子ID必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
            } catch (SQLException e) {
                e.printStackTrace(); // 打印完整堆栈信息
                JOptionPane.showMessageDialog(this, "添加失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    // 验证柜子ID是否存在
    private boolean validateLockerExists(int lockerId) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement("SELECT COUNT(*) FROM lockers WHERE id = ?")) {

            ps.setInt(1, lockerId);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next() && rs.getInt(1) > 0) {
                    return true;
                }
            }
            JOptionPane.showMessageDialog(this, "无效的柜子ID，请重新输入", "错误", JOptionPane.ERROR_MESSAGE);
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "验证柜子失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }

    private void deleteSelected() {
        int row = table.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的记录", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int id = (int) model.getValueAt(row, 0);
        int confirm = JOptionPane.showConfirmDialog(this, "确定删除该记录？", "确认", JOptionPane.YES_NO_OPTION);

        if (confirm == JOptionPane.YES_OPTION) {
            try (Connection conn = DBUtil.getConnection();
                 PreparedStatement ps = conn.prepareStatement("DELETE FROM send_express WHERE id = ?")) {

                ps.setInt(1, id);
                ps.executeUpdate();
                JOptionPane.showMessageDialog(this, "记录已删除", "成功", JOptionPane.INFORMATION_MESSAGE);
                loadData();
            } catch (SQLException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "删除失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}